# -*- coding: utf-8 -*-
import re
import mechanize
from BeautifulSoup import BeautifulSoup

url_host = "http://localhost:8080"
url_app = "%s/partymgr/control" % url_host
filename='test-td-party.xls'

import pprint
pp = pprint.PrettyPrinter(indent=2)

def applyDict2Form(_br, _form_name, _dict): 
    _br.select_form(name=_form_name)
    f = _br.form
    for kk in _dict: 
        if type(_dict[kk]) is unicode: v = _dict[kk].encode('utf-8')
        elif not _dict.has_key(kk) or _dict[kk] is None: v = ''
        else: v=_dict[kk]
        c=f.find_control(name=kk)
        if c.__class__.__name__=='SelectControl': f[kk]=v and [v] or []
        elif c.__class__.__name__=='HiddenControl': c._value=v
        else: f[kk]=v

def page_get_id_and_soup(page):
    soup = BeautifulSoup(page, convertEntities=BeautifulSoup.HTML_ENTITIES)
    title = soup.find('div', {'class':'page-title'}) # ok
    id = None
    if title: 
        m = re.search(r'\[([^\]]+)\]', title.find('span').getText())
        if m: id = m.groups()[0]
    print "---> new id %s" % id
    return (id, soup)

def page_soup_error(soup):
    cm = soup.find('div', {'id':'content-messages'}) # error
    if cm:
        print cm.getText()
        return True
    return False

def page_get_error(page):
    soup = BeautifulSoup(page, convertEntities=BeautifulSoup.HTML_ENTITIES)
    return page_soup_error(soup)

br = mechanize.Browser()

# login
br.open("%s/login" % url_app)
br.select_form(name="loginform")
br.form['USERNAME']='admin'
br.form['PASSWORD']='ofbiz'
res = br.submit()
br.open("%s/projectmgr/control/login" % url_host)
br.select_form(name="loginform")
br.form['USERNAME']='admin'
br.form['PASSWORD']='ofbiz'
res = br.submit()

mcc = { '_':['master','employees'],
     'master':{
         'company':['A^1',u'公司'],
         'tel':['A^2',u'電話'],
         'postArea':['A^3',u'郵遞區號'],
         'city':['C^3',u'城市'],
         'addr':['E^3',u'地址'],
     },
     'employees':{
         '*':{
             'id':['A1',u'ID'],
             'lname':['B1',u'姓氏'],
             'fname':['C1',u'名字'],
             'ext':['D1',u'分機'],
             'mobile':['E1',u'手機'],
             'home':['F1',u'住家電話'],
             'job':['G1',u'職務'],
             'rate':['H1',u'費率'],
         },
     },
}
from tabledown.tdxls import TDXls
tdx = TDXls(mcc)
data = tdx.xls2dict(filename)
#pp.pprint(data)


def tw_local_phone(tel):
    tel_area, tel_local, tel = re.match('(\d+)-(\d+)|(\d+)', tel).groups()
    return (tel_area and tel_area or '', tel_local and tel_local or tel)

def formal_mobile(tel):
    tel_no_zero_leads, tel = re.match('0(\d+)|(\d+)', tel).groups()
    return tel_no_zero_leads and tel_no_zero_leads or tel

sheet1 = data.values()[0]

# get data from sheet
master = sheet1['master']
employees = sheet1['employees']

master_keys = ('company','tel','postArea','city','addr')
employee_keys = ('id','lname','fname','ext','home','mobile','job','rate')

# company data
mCompany, mTel, mPostalCode, mCity, mAddr = map(master.get, master_keys)
mTelArea, mTel = tw_local_phone(mTel)
print mCompany, "(%s)%s" % (mTelArea, mTel), mPostalCode, mCity, mAddr
for employee in employees:
    # employee data
    eId, eLname, eFname, eExt, eHome, eMobile, eJob, eRate = map(employee.get, employee_keys)
    eHomeArea, eHome = tw_local_phone(eHome)
    eMobile = formal_mobile(eMobile)
    print eId, eLname, eFname, eExt, "(%s)%s" % (eHomeArea, eHome), eMobile, eJob, eRate
    dEmployee = {'USE_ADDRESS': 'USE_ADDRESS','require_email': 'require_email',
        'USER_LAST_NAME': eLname, 'USER_FIRST_NAME': eFname,
        'USER_CITY': mCity, 'USER_ADDRESS1': mAddr,
        'USER_POSTAL_CODE': mPostalCode, 
        'USER_COUNTRY': 'TWN', 'USER_STATE': '',
        'USER_HOME_COUNTRY': '886', 'USER_HOME_AREA': eHomeArea, 
        'USER_HOME_CONTACT': eHome,
        'USER_WORK_COUNTRY': '886', 'USER_WORK_AREA': mTelArea, 
        'USER_WORK_CONTACT': mTel, 'USER_WORK_EXT': eExt,
        'USER_MOBILE_COUNTRY': '886', 'USER_MOBILE_AREA': '0', 
        'USER_MOBILE_CONTACT': eMobile,
        'USER_EMAIL': "%s@side.org" % eId,
        'USERNAME': eId, 'PASSWORD': 'ofbiz', 'CONFIRM_PASSWORD': 'ofbiz',
        'PRODUCT_STORE_ID': 'jia', }

    # create employee
    br.open("%s/createEmployee" % url_app)
    applyDict2Form(br, 'NewUser', dEmployee)
    res = br.submit()
    id, soup = page_get_id_and_soup(res.get_data())
    if not id and page_soup_error(soup): break # error
    
    # assign roles
    br.open("%s/viewroles?partyId=%s" % (url_app, id))
    dRole = {'partyId': id, 'roleTypeId': 'PROJECT_TEAM'}
    applyDict2Form(br, 'AddPartyMainRole', dRole)
    res = br.submit()
    if page_get_error(res.get_data()): break # error
    role_ti={'ACC':'PROVIDER_ACCOUNTING', 
        'SA':'PROVIDER_ANALYST',
        'PG':'PROVIDER_FUNCTIONAL',
        'PM':'PROVIDER_MANAGER', 
        'TEST':'PROVIDER_TESTER',
        'QA':'PROVIDER_VALIDATOR'}.get(eJob, 'PROVIDER_FUNCTIONAL')
    dRole = {'partyId': id, 'roleTypeId': role_ti}
    applyDict2Form(br, 'AddPartyRole', dRole)
    res = br.submit()
    if page_get_error(res.get_data()): break # error

    # assign rate
    br.open("%s/projectmgr/control/EditPartyRates?partyId=%s" % (url_host, id))
    applyDict2Form(br, 'AddPartyRate', {'rateAmount': eRate})
    res = br.submit()
    if page_get_error(res.get_data()): break # error

# logout
br.open("%s/logout" % url_app)
br.open("%s/projectmgr/contro/logout" % url_host)
